<template>
  <div class="product-management">
    <div class="page-header">
      <div class="header-left">
        <el-button type="primary" @click="router.push('/')">
          <el-icon><ArrowLeft /></el-icon>
          返回主页
        </el-button>
      </div>
      <div class="header-center">
        <h2>农产品管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建农产品
        </el-button>
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="productList"
      style="width: 100%"
      border
    >
      <el-table-column label="商品图片" width="100">
        <template #default="scope">
          <el-image
            :src="scope.row.productImage"
            fit="cover"
            style="width: 80px; height: 80px"
            :preview-src-list="[scope.row.productImage]"
          />
        </template>
      </el-table-column>
      <el-table-column prop="productId" label="商品ID" width="80" />
      <el-table-column prop="name" label="商品名称" width="120" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="scope">
          ¥{{ scope.row.price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" width="80" />
      <el-table-column prop="description" label="描述" show-overflow-tooltip />
      <el-table-column prop="farmName" label="所属农场" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
            {{ scope.row.status === 1 ? '上架中' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="200">
        <template #default="scope">
          <el-button
            :type="scope.row.status === 1 ? 'danger' : 'success'"
            size="small"
            @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === 1 ? '下架' : '上架' }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next"
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 编辑商品对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="editForm.productId ? '编辑商品' : '新增商品'"
      width="50%"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="商品名称" required>
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="价格" required>
          <el-input-number v-model="editForm.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="库存" required>
          <el-input-number v-model="editForm.stock" :min="0" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.description" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, ArrowLeft, Plus } from '@element-plus/icons-vue'
import { getAllProductsForAdmin, updateProductStatus, updateProduct } from '@/api/product'

const router = useRouter()
const loading = ref(false)
const productList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const editDialogVisible = ref(false)
const editForm = ref({
  productId: null,
  name: '',
  price: 0,
  stock: 0,
  description: ''
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString()
}

// 获取商品列表
const getProductList = async () => {
  loading.value = true
  try {
    const res = await getAllProductsForAdmin()
    console.log('获取到的商品列表数据:', res)
    if (Array.isArray(res)) {
      productList.value = res.map(item => ({
        productId: item.productId,
        name: item.productName,
        price: item.price,
        stock: item.stock,
        description: item.productDescription,
        farmName: item.farmName,
        createTime: item.createdAt,
        status: item.status,
        farmId: item.farmId,
        productImage: item.productImage
      }))
      total.value = productList.value.length
    } else {
      ElMessage.error('获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  getProductList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getProductList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getProductList()
}

// 处理商品状态变更
const handleStatusChange = async (product) => {
  try {
    await ElMessageBox.confirm(
      `确定要${product.status === 1 ? '下架' : '上架'}该商品吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updateProductStatus(product.productId, product.status === 1 ? 0 : 1)
    
    ElMessage.success('操作成功')
    getProductList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新商品状态失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 打开编辑对话框
const handleEdit = (product) => {
  editForm.value = {
    productId: product.productId,
    name: product.name,
    price: product.price,
    stock: product.stock,
    description: product.description
  }
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    if (!editForm.value.name || editForm.value.price === null || editForm.value.stock === null) {
      ElMessage.warning('请填写必填项')
      return
    }
    
    await updateProduct(editForm.value)
    
    ElMessage.success('保存成功')
    editDialogVisible.value = false
    getProductList()
  } catch (error) {
    console.error('保存商品失败:', error)
    ElMessage.error('保存失败')
  }
}

onMounted(() => {
  getProductList()
})
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
}

.header-left {
  flex: 1;
}

.header-center {
  flex: 2;
  text-align: center;
}

.header-center h2 {
  margin: 0;
  font-size: 24px;
  color: #409EFF;
}

.header-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 